package com.chenxbook.modules.examples.eventlistener;

import lombok.extern.slf4j.Slf4j;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;

/**
 * 事件监听必须实现EventListener
 * <br> 退回场景的流程定义，新增一条用于退回的路径
 */
@Slf4j
public class RollbackListener implements EventListener {

    private static final long serialVersionUID = 30044957906215717L;

    //退回目的地，通过流程定义注入
    String m_rollbackTo;

    /**
     * 增加一条用于退回的路径
     */
    @Override
    public void notify(EventListenerExecution execution) throws Exception {
        // 首先获取流程定义对象 - processDefinition
        ProcessInstance processInstance = execution.getProcessInstance();
        String processDefinitionId = processInstance.getProcessDefinitionId();
        ProcessDefinitionImpl processDefinition = ((ExecutionImpl) execution).getProcessDefinition();
        //获取退回目的地的活动定义对象
        ActivityImpl toActivityImpl = processDefinition.findActivity(m_rollbackTo);
        if (toActivityImpl == null) {
            //如果退回目的地活动不存在，则属于流程定义错误。
            String msg = "In " + processDefinitionId + " no " + m_rollbackTo;
            log.warn(msg);
            throw new Exception(msg);
        }
        //获取当前活动定义对象
        ActivityImpl fromActivityImp = ((ExecutionImpl) execution).getActivity();
        //在这里建立退回的转移路径
        TransitionImpl transition = fromActivityImp.createOutgoingTransition();
        transition.setName(fromActivityImp.getName() + " to " + m_rollbackTo);
        transition.setDestination(toActivityImpl);
    }
}
